//
//  YZXEmojticonView.swift
//  表情键盘
//
//  Created by 叶周翔 on 16/7/28.
//  Copyright © 2016年 叶周翔. All rights reserved.
//

import UIKit

enum EmoticonToolBarType:Int{
    
    case Recent  = 0   // 最近使用
    case Default = 1   // 默认
    case Emoji   = 2   // 表情
    case LXH     = 3   //浪小花
}

protocol emojticonViewDelegate :NSObjectProtocol{
    
    func emojticonToolBar(didSelecedType type:EmoticonToolBarType)
    
}

class YZXEmojticonView: UIView {
    // 代理属性
    var delegate:emojticonViewDelegate?
    
    private var buttons: [YZXButton] = [YZXButton]()
    // 选中了哪个按钮
    private var selectBtn:YZXButton?
    // MARK: view的生命周期
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setUI()
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        // 给四个按钮设置frame
        let buttonWidth = self.frame.width / CGFloat(buttons.count)
        let buttonHeight = self.frame.height
        for (index,button) in buttons.enumerate(){
            button.frame = CGRectMake(CGFloat(index) * buttonWidth, 0, buttonWidth, buttonHeight)
        }
    }
    // MARK: 设置view
    private func setUI() {
        let names = ["最近", "默认", "emoji", "浪小花"]
        for (index,name) in names.enumerate() {
            let button = YZXButton()
            button.setTitle(name, forState: UIControlState.Normal)
            button.setBackgroundImage(UIImage(named: "compose_emotion_table_mid_normal"), forState: UIControlState.Normal)
            button.setBackgroundImage(UIImage(named: "compose_emotion_table_mid_selected"), forState: UIControlState.Disabled)
            
            // 点击事件
            button.addTarget(self, action: "btnDidClick:", forControlEvents: UIControlEvents.TouchUpInside)
            button.tag = index
            self.addSubview(button)
            buttons.append(button)
            
            // 默认选中第0组第0行
            if index == 0 {
                btnDidClick(button)
            }
        }
    }
    // MARK:按钮的点击事件
    @objc private func btnDidClick(btn:YZXButton){
        // 匹配点击的是哪一个按钮
        switchButton(btn)
        // 代理调用
        let type = EmoticonToolBarType(rawValue: btn.tag)!
        delegate?.emojticonToolBar(didSelecedType: type)
        
    }
    
    func choseButtonWithIndexPath(section:Int){
        let button = buttons[section]
        switchButton(button)
    }
    
    
    private func switchButton(btn:YZXButton){
       selectBtn?.enabled = true
        btn.enabled = false
        // 保存按钮
        selectBtn = btn
    }
    
    
}